package com.neusoft.hifly.information.power.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.annotation.LogType;
import com.neusoft.hifly.core.log.annotation.OperationLog;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;
import com.neusoft.hifly.information.power.dao.IColumnPowerDao;
import com.neusoft.hifly.information.power.entity.ColumnPowerObj;
import com.neusoft.hifly.information.power.service.IColumnPowerService;

/**
 * Title: 文章资讯服务
 * <p>
 * Description: 栏目权限 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class ColumnPowerServiceImpl extends CTSaaSBaseServiceImpl implements IColumnPowerService {
	@Autowired(required = false)
	private IColumnPowerDao columnPowerDao;

	/**
	 * 保存对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@OperationLog(method = LogType.UPDATE, msg = "栏目权限")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final String organCode, final long organLogicId, final ColumnPowerObj obj)
			throws SystemErrorException {
		if (StringUtils.isEmpty(organCode) || obj == null) {
			return;
		}
		if (StringUtils.isEmpty(obj.getOrganCode())) {
			obj.setOrganCode(organCode);
		}
		if (LongUtil.isEmpty(obj.getOrganLogicId())) {
			obj.setOrganLogicId(organLogicId);
		}

		final ColumnPowerObj oldObj = columnPowerDao.getByLogicId(organCode, organLogicId, obj.getLogicId());

		obj.setOrganLogicId(organLogicId);

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			obj.setId(idWorker.nextId());
			if (LongUtil.isEmpty(obj.getLogicId())) {
				obj.setLogicId(idWorker.nextId());
			}
			obj.setUpdateTime(LocalDateTime.now());

			if (StringUtils.isEmpty(obj.getUpdatePerson())) {
				obj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			this.setForm(obj, obj);

			columnPowerDao.insert(obj);

		} else {
			// 更新

			this.setForm(obj, oldObj);

			oldObj.setUpdateTime(LocalDateTime.now());
			if (StringUtils.isEmpty(oldObj.getUpdatePerson())) {
				oldObj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			columnPowerDao.updateById(oldObj);

		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象ID
	 */
	@Override
	@OperationLog(method = LogType.DELETE, msg = "栏目权限")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		columnPowerDao.deleteByLogicId(organCode, organLogicId, logicId);
	}

	/**
	 * 批量删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicIds
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String organCode, final long organLogicId, final String logicIds) {
		if (StringUtils.isEmpty(organCode) || StringUtils.isEmpty(logicIds)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String logicId : logicIdArr) {
			if (StringUtils.isEmpty(logicId)) {
				continue;
			}
			this.deleteByLogicId(organCode, organLogicId, Long.parseLong(logicId));
		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param columnLogicId
	 *            栏目ID
	 * @param objId
	 *            对象ID
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByColumnLogicId(final String organCode, final long organLogicId, final long columnLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		columnPowerDao.deleteByColumnLogicId(organCode, organLogicId, columnLogicId);
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param columnLogicId
	 *            栏目ID
	 * @param objId
	 *            对象ID
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByObjLogicId(final String organCode, final long organLogicId, final long columnLogicId,
			final long objId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		columnPowerDao.deleteByObjLogicId(organCode, organLogicId, columnLogicId, objId);
	}

	/**
	 * 删除栏目权限
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param columnLogicId
	 *            栏目逻辑ID
	 * @param powerObjIds
	 *            权限对象ID串，多id使用英文逗号分隔
	 */
	@Override
	public void deleteColumnPowers(final String organCode, final long organLogicId, final long columnLogicId,
			final String powerObjIds) {
		if (StringUtils.isEmpty(powerObjIds)) {
			return;
		}
		final String[] logicIdArr = powerObjIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String objId : logicIdArr) {
			if (StringUtils.isEmpty(objId)) {
				continue;
			}
			this.deleteByObjLogicId(organCode, organLogicId, columnLogicId, Long.parseLong(objId));
		}
	}

	/**
	 * 根据id查询对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	public ColumnPowerObj getByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return columnPowerDao.getByLogicId(organCode, organLogicId, logicId);
	}

	/**
	 * 查询所有对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @return 对象集合
	 */
	@Override
	public List<ColumnPowerObj> findAll(final String organCode, final long organLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return columnPowerDao.findAll(organCode, organLogicId);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<ColumnPowerObj> search(final String organCode, final long organLogicId, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final QueryWrapper<ColumnPowerObj> queryWrapper = new QueryWrapper<ColumnPowerObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "UPDATE_TIME" });
		return columnPowerDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public IPage<ColumnPowerObj> search(final String organCode, final long organLogicId, final int offset,
			final int limit, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final IPage<ColumnPowerObj> page = new Page<ColumnPowerObj>(offset, limit);
		final QueryWrapper<ColumnPowerObj> queryWrapper = new QueryWrapper<ColumnPowerObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "UPDATE_TIME" });
		return columnPowerDao.selectPage(page, queryWrapper);
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final ColumnPowerObj fromObj, final ColumnPowerObj toObj) {
		toObj.setOrganLogicId(fromObj.getOrganLogicId());
		toObj.setColumnLogicId(fromObj.getColumnLogicId());
		toObj.setObjType(StringUtils.trimToEmpty(fromObj.getObjType()));
		toObj.setObjId(fromObj.getObjId());
		toObj.setObjName(StringUtils.trimToEmpty(fromObj.getObjName()));
		toObj.setExt1(StringUtils.trimToEmpty(fromObj.getExt1()));
		toObj.setExt2(StringUtils.trimToEmpty(fromObj.getExt2()));
		toObj.setExt3(StringUtils.trimToEmpty(fromObj.getExt3()));
		toObj.setExt4(StringUtils.trimToEmpty(fromObj.getExt4()));
		toObj.setExt5(StringUtils.trimToEmpty(fromObj.getExt5()));

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("organLogicId")) {
				property.put("ORGAN_LOGIC_ID", property.get("organLogicId"));
				property.remove("organLogicId");
			}
			if (property.containsKey("columnLogicId")) {
				property.put("COLUMN_LOGIC_ID", property.get("columnLogicId"));
				property.remove("columnLogicId");
			}
			if (property.containsKey("objType")) {
				property.put("OBJ_TYPE", property.get("objType"));
				property.remove("objType");
			}
			if (property.containsKey("objId")) {
				property.put("OBJ_ID", property.get("objId"));
				property.remove("objId");
			}
			if (property.containsKey("objName")) {
				property.put("OBJ_NAME", property.get("objName"));
				property.remove("objName");
			}
			if (property.containsKey("updatePerson")) {
				property.put("UPDATE_PERSON", property.get("updatePerson"));
				property.remove("updatePerson");
			}
			if (property.containsKey("updateTime")) {
				property.put("UPDATE_TIME", property.get("updateTime"));
				property.remove("updateTime");
			}
			if (property.containsKey("ext1")) {
				property.put("EXT1", property.get("ext1"));
				property.remove("ext1");
			}
			if (property.containsKey("ext2")) {
				property.put("EXT2", property.get("ext2"));
				property.remove("ext2");
			}
			if (property.containsKey("ext3")) {
				property.put("EXT3", property.get("ext3"));
				property.remove("ext3");
			}
			if (property.containsKey("ext4")) {
				property.put("EXT4", property.get("ext4"));
				property.remove("ext4");
			}
			if (property.containsKey("ext5")) {
				property.put("EXT5", property.get("ext5"));
				property.remove("ext5");
			}

		}
	}
}